package com.luoling.download;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.luoling.util.DateUtils;
import com.luoling.util.JsonUtils;
import lombok.Data;
import org.apache.poi.util.StringUtil;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Description:
 * Copyright:   Copyright (c)2024
 * Company:
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2024-07-17 17:31:17
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2024-07-17     张李鑫                     1.0         1.0 Version
 */
public class DownLoadDetailSql {
    private static ObjectMapper mapper = null;


    /**
     * {
     * "id": "2c90858090bfc47f0190bff91c52011a",
     * "name": "1721206923198总账、指标13",
     * "uploadType": 1,
     * "isReportToGroup": 0,
     * "scriptType": 1,
     * "isBackup": 0,
     * "status": 3,
     * "statusName": "查询成功",
     * "dataSourceGroupIdList": [
     * "2c9086ce8c62fcb1018c63ae11fd0065"
     * ],
     * "startTime": "2024-07-17 17:15:48",
     * "finishTime": "2024-07-17 17:16:06",
     * "createTime": "2024-07-17 17:14:52",
     * "updateTime": "2024-07-17 17:16:05",
     * "appSystem": {
     * "id": 1,
     * "name": "transferquota119"
     * }
     * },
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            System.out.println("参数为空");
            return;
        }
        mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


        DownLoadDetail downLoadDetail = readConfig(args);
        HashMap<String, String> params = new HashMap<>();
        params.put("Cookie", downLoadDetail.getCookie());
        params.put("Referer", downLoadDetail.getRef());
        params.put("X-Auth-Token", downLoadDetail.getAuthToken());
        params.put("User-Agent", downLoadDetail.getUserAgent());
        List<Model> list = list(downLoadDetail, params);

        CountDownLatch countDownLatch = new CountDownLatch(list.size());


        for (Model model : list) {
            new Thread(()->{
                try {
                    String res = downLoad(model, params);
                    String path=System.getProperty("user.dir") + File.separator + DateUtils.dateTime() + File.separator;
                    Files.createDirectories(Paths.get(path));
                    writeToFile(System.getProperty("user.dir") + File.separator + DateUtils.dateTime() + File.separator +  model.getName().replace("?","") + ".sql", res);
                    countDownLatch.countDown();
                } catch (Exception e) {
                   e.printStackTrace();
                }
            }).start();

        }
        countDownLatch.await();
    }

    public static void writeToFile(String fileName, String content) {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String downLoad(Model model, HashMap<String, String> params) throws Exception {
        String url = "http://prod.db-upgrade-tools.ctjsoft.com/api/v1/dataTransmission/export/globalFile/" + model.getId();
        return HttpUtil.sendGet(url, params);
    }

    public static List<Model> list(DownLoadDetail detail, HashMap<String, String> params) throws Exception {
        String listUrl = getListUrl(detail);
        String json = HttpUtil.sendGet(listUrl, params);
        Res<List<Model>> res = JsonUtils.toObject(json, Res.class);
        return mapper.convertValue(res.getData(), new TypeReference<List<Model>>() {
        });
    }

    public static String getListUrl(DownLoadDetail detail) {
        //http://prod.db-upgrade-tools.ctjsoft.com/api/v1/upgradePackage?&SystemId=25
        //http://prod.db-upgrade-tools.ctjsoft.com/api/v1/upgradePackage?&appSystemId=25
        String listUrl = "http://prod.db-upgrade-tools.ctjsoft.com/api/v1/upgradePackage?page=" + detail.getPage() + "&size=" + detail.getPageSize() + "&uploadType=" + detail.getUploadType();
        String systemId = detail.getSystemId();

        if (!StringUtil.isBlank(systemId)) {
            listUrl += "&appSystemId=" + systemId;
        }
        if (!StringUtil.isBlank(detail.getName())) {
            listUrl += "&name=" + detail.getName();
        }
        if (!StringUtil.isBlank(detail.getStatus())) {
            listUrl += "&status=" + detail.getStatus();
        }
        System.out.println("list url =" + listUrl);
        return listUrl;
    }

    public static DownLoadDetail readConfig(String[] args) throws Exception {
        if (args.length == 0) {
            throw new RuntimeException("没有参数");
        }
        if (args.length < 2 || !args[0].equals("--config")) {
            System.err.println("Usage: java -jar MyApp.jar --config /path/to/config.properties");
            System.exit(1);
        }
        String configPath = args[1];
        if (configPath.contains("./")) {
            configPath = System.getProperty("user.dir") + File.separator + configPath.replace("./", "");
        }
        FileReader reader = new FileReader(configPath);
        JsonNode jsonNode = JsonUtils.MAPPER.readTree(reader);
        return JsonUtils.MAPPER.treeToValue(jsonNode, DownLoadDetail.class);

    }


    @Data
    public static class DownLoadDetail extends Base{
        private String listUrl;
        private String downLoadUrl;
        private String json;
        private String systemId;
        private Integer pageSize;
        private String name;
        private String status;
        private Integer page;
        private Integer uploadType;
    }

    @Data
    public static class Model {
        private String id;
        private String name;
    }

    @Data
    public static class Res<T> {
        private Integer totalData;
        private Integer totalPages;
        private T data;
    }
}
